package com.zjh.common.security.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zjh.common.entity.LoginUser;
import com.zjh.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author zhangjinghua
 */
@Service
@Slf4j
public class MyTokenService {

    @Value("${spring.security.token.header:Authorization}")
    private String header;


    @Resource
    private JwtUtil jwtUtil;

    public LoginUser parseToken(HttpServletRequest request) {
        String jwt = getJwt(request);
        if (jwt != null) {
            return jwtUtil.parseToken(jwt);
        }
        return null;
    }

    private String getJwt(HttpServletRequest request) {
        String jwt = request.getHeader(header);
        if (StringUtils.isBlank(jwt)) {
            return null;
        }
        if (jwt.startsWith("Bearer ")) {
            jwt = jwt.replace("Bearer ", "");
        }
        return jwt;
    }


    public String newToken(LoginUser loginUser) {
        loginUser.setTokenId(IdUtil.randomUUID());
        String jwt = jwtUtil.generateToken(loginUser);
        return jwt;
    }

}
